package cn.chint.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.JsonObject;

import cn.chint.po.SysUser;


/**
 * chengsheng
 * 跨域请求处理
 */
public class CORSFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    } 
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Expose-Headers", "*");
//        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
//        response.setHeader("Access-Control-Max-Age", "3600");
//        response.setHeader("Access-Control-Allow-Headers", "*");
//        response.setHeader("Access-Control-Allow-Credentials", "true");
        
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        response.setContentType("text/html;charset=UTF-8");
//        
//        System.out.println(request.getServerName());
//        System.out.println(request.getServerPort());
//        System.out.println(request.getContextPath());
//        System.out.println(request.getServletPath());
//        System.out.println(request.getPathInfo());
        System.out.println(request.getRequestURI());
       
        
        if(request.getRequestURI().contains("userLogin") ){
        	filterChain.doFilter(servletRequest, servletResponse);
    }
    else{
    	
    	SysUser sysUser = (SysUser)request.getSession().getAttribute("sysUser");
    	if(sysUser==null){
    		com.alibaba.fastjson.JSONObject jsonObj = new com.alibaba.fastjson.JSONObject();
        	//jsonObj.put("statusCode", 304);
        	jsonObj.put("status", false);
        	jsonObj.put("msg", "用户已失效，请重新登录");
        	
    		PrintWriter out  = response.getWriter();
    		out.print(jsonObj.toString());
    		//response.setStatus(403);
    		//response.sendRedirect(request.getContextPath() + "/login.html");
    	}
    	else{
    		filterChain.doFilter(servletRequest, servletResponse);
    	}
    }
    }


    @Override
    public void destroy() {

    }
}















